package com.woniuxy.service.impl;

import com.woniuxy.dao.AccountMapper;
import com.woniuxy.dao.TranRecordMapper;
import com.woniuxy.pojo.Account;
import com.woniuxy.pojo.TranRecord;
import com.woniuxy.service.AccountService;
import com.woniuxy.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Spring的事务要在业务层中添加，主要的目的是实现业务层中方法的内容原子性
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private TranRecordMapper tranRecordMapper;
    //@Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public boolean transfer(String fromAccountno, String toAccountno, float money) throws Exception{
        boolean flag=false;
        //查询转账者的账户
        Account fromAccount=accountMapper.selectAccountByAccountno(fromAccountno);
        fromAccount.setBalance(fromAccount.getBalance()-money);
        //更新转账者账户余额
        accountMapper.updateAccountByAccountno(fromAccount);
        //模拟延时操作
        //Thread.sleep(5000);
        //模拟检查异常
        //InputStream in=new FileInputStream("c:\\aa.txt");
        //查询收款者的账户
        Account toAccount=accountMapper.selectAccountByAccountno(toAccountno);
        toAccount.setBalance(toAccount.getBalance()+money);
        //更新收款者账户余额
        accountMapper.updateAccountByAccountno(toAccount);

        //实例化转账者的动账实体对象
        TranRecord fromTranRecord=new TranRecord();
        fromTranRecord.setType(-1);//type为-1表示支出,type为1表示收款
        fromTranRecord.setMoney(-money);
        fromTranRecord.setAccountno(fromAccountno);
        fromTranRecord.setMessage("借记卡"+fromAccountno+"支出"+money+"元,"+ DateUtil.formatDate(new Date()));
        //完成增加记录
        tranRecordMapper.insertRecord(fromTranRecord);
        //实例化收款者的动账实体对象
        TranRecord toTranRecord=new TranRecord();
        toTranRecord.setType(1);//type为-1表示支出,type为1表示收款
        toTranRecord.setMoney(money);
        toTranRecord.setAccountno(toAccountno);//此时设置对方的账号
        toTranRecord.setMessage("借记卡"+toAccountno+"存入"+money+"元,"+ DateUtil.formatDate(new Date()));
        //完成增加记录
        tranRecordMapper.insertRecord(toTranRecord);
        flag=true;
        return flag;
    }
    //@Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public Account findAccountByAccountno(String accountno) {
        return this.accountMapper.selectAccountByAccountno(accountno);
    }
}
